package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.enums.ColumnExceptionEnum;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.WebsiteAddr;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_ARTICLE_LIST;

/**
 * @ClassName ArticleListDirective
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/21 11:11
 * @Version 1.0
 */
@Component
public class ArticleListDirective extends AbstractDirective {

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;


    @Value("${cms.realPath}")
    private String Path;

    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";

    /**
     * 当前分类的文章列表
     */
    public static final String COLUMN_ARTICLE_LIST = "articleList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        Map<String, Object> localEnviroment = EnvironmentContextHolder.getEnvironment();
        try {
            // /Mr.zheng:获取参数
            Long columnId = Long.parseLong((String) localEnviroment.get("columnId"));
            Long siteId = Long.parseLong((String) localEnviroment.get("siteId"));
            Long page = Long.parseLong((String) localEnviroment.get("pageNum"));
            int pageNum = page == null ? 1 : (Integer) getCustomAttrbute(env, "pageNum");

            if (columnId == null) {
                throw new CustomException(ColumnExceptionEnum.COLUMN_NOT_EXIST);
            }

            Column column = new Column();
            column.setColumnId(columnId);
            column.setSiteId(siteId);
            // Mr.zheng:封装当前选中的分类信息
            column = columnServiceClient.getColumn(column);
            String note = super.getNote(env);
            if (StringUtils.isNotBlank(note)) {
                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
            }

            ResultPageStruct<Article> resultPageStruct = getArticleResultPageStruct(pageNum, column);//获取当前分类下的文章列表
            List<Article> articleList = resultPageStruct.getData();
            if (StringUtils.isNotBlank(note)) {
                for (Article article : articleList) {
                    article.setManuscriptPath(Path + article.getManuscriptPath());
                }
            }else {
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                for (Article item : articleList) {
                    // 静态文件文章链接加前缀
                    String urlContext = siteCtxMap.get(item.getSiteId());
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }
            env.setVariable(COLUMN_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_ARTICLE_LIST, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_ID, String.valueOf(super.getLong(COLUMN_ID, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取当前分类下的文章列表
    public ResultPageStruct<Article> getArticleResultPageStruct(int pageNum, Column column) throws Exception {
        PageTo pageParam = new PageTo();
        pageParam.setPageNum(pageNum);
        pageParam.setPageSize(column.getPageSize() == null ? 5 : column.getPageSize());

        Article article = new Article();
        article.setColumnId(column.getColumnId());
        article.setSiteId(column.getSiteId());
        article.setAuditType(0);
        article.setDelTag(0);

        ParameterDataStruct<Article> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(article);
        parameterDataStruct.setPageTo(pageParam);
        return articleServiceClient.getArticleList(parameterDataStruct);
    }


}
